package com.jzr.medical.auth;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class MyAuthenticationException implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        /*
        httpServletResponse.setStatus(200);
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        PrintWriter printWriter = httpServletResponse.getWriter();
        httpServletResponse.getWriter().write("异常:" + e);
        printWriter.flush();
        */
        //response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
        Integer vStatus = (Integer)request.getAttribute("vStatus");
        String vMessage = (String)request.getAttribute("vMessage");
        if(vStatus == null){
            vStatus = HttpServletResponse.SC_UNAUTHORIZED;
        }
        if(vMessage == null){
            vMessage = e.getMessage();
        }
        response.setStatus(vStatus);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        int code = vStatus;
        String msg = vMessage;
        out.write("{\"code\":" + code + ",\"status\":" + code + ",\"msg\":\"" + msg + "\"" + ",\"message\":\"" + msg + "\"}");
        out.flush();
        out.close();
    }
}
